﻿#include "MyUtils.h"


// 显示错误的消息
std::string GetSysErrorString(DWORD errorCode) {

	std::ostringstream oss;

	// 使用 FormatMessage 转换错误码为字符串  
	LPSTR messageBuffer = nullptr;
	FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

	// 输出错误信息  
	//std::cout << "[Error-" << errorCode << "]: " << messageBuffer << std::endl;
	oss << "[Error-" << errorCode << "]:" << messageBuffer << std::endl;

	// 释放分配的内存  
	LocalFree(messageBuffer);

	return oss.str();
}

HANDLE CheckHandle(HANDLE hHandle, const char* file, int line) {
	if (hHandle == nullptr)
	{
		std::ostringstream oss;
		oss << "hHandle is null!" << std::endl;
		oss << "[File]:" << file << std::endl;
		oss << "[Line]:" << line << std::endl;
		int errorCode = GetLastError();
		oss << GetSysErrorString(errorCode) << std::endl;
		throw std::runtime_error(oss.str());
	}
	return hHandle;
}
void CheckHRESULT(HRESULT hr, const char* file, int line) {
	if (FAILED(hr))
	{
		std::ostringstream oss;
		oss << "hr failed!" << std::endl;
		oss << "[File]:" << file << std::endl;
		oss << "[Line]:" << line << std::endl;
		int errorCode = GetLastError();
		oss << GetSysErrorString(errorCode) << std::endl;
		throw std::runtime_error(oss.str());
	}
}

void Assert(bool flag, const char* msg, const char* file, int line) {
	if (!flag)
	{
		std::ostringstream oss;
		oss << "msg:" << msg << std::endl;
		oss << "[File]:" << file << std::endl;
		oss << "[Line]:" << line << std::endl;
		throw std::runtime_error(oss.str());
	}
}
